const SECRET_KEY = import.meta.env.VITE_SECRET_KEY || 'medicine-ecommerce-secret-key'

// 添加密钥轮换机制
const getCurrentKey = () => {
  const date = new Date()
  const day = date.getDate()
  return `${SECRET_KEY}-${day}`
}

/**
 * 简单加密方法，用于一般数据加密
 * @param {string|object} text 需要加密的文本或对象
 * @returns {string} 加密后的字符串
 */
export const encrypt = (text) => {
  try {
    const textToEncrypt = typeof text === 'object' ? JSON.stringify(text) : text;
    const currentKey = getCurrentKey();
    
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
    const applySaltToChar = code => textToChars(currentKey).reduce((a, b) => a ^ b, code);

    return textToEncrypt.split('')
      .map(textToChars)
      .map(applySaltToChar)
      .map(byteHex)
      .join('');
  } catch (error) {
    console.error('加密失败:', error);
    return null;
  }
}

/**
 * 解密方法
 * @param {string} encoded 加密后的字符串
 * @returns {string|object|null} 解密后的内容，失败时返回null
 */
export const decrypt = (encoded) => {
  try {
    // 边界检查
    if (!encoded || typeof encoded !== 'string') {
      console.warn('解密失败: 无效的输入数据');
      return null;
    }
    
    // 处理带引号的情况
    let cleanEncoded = encoded;
    if (encoded.startsWith('"') && encoded.endsWith('"')) {
      try {
        cleanEncoded = JSON.parse(encoded);
      } catch (e) {
        // 如果解析失败，继续使用原始字符串
      }
    }
    
    // 处理空格和特殊字符
    cleanEncoded = cleanEncoded.replace(/\s/g, '');
    
    // 检查是否为有效的十六进制字符串
    if (!/^[0-9a-fA-F]+$/.test(cleanEncoded)) {
      console.warn('解密失败: 输入不是有效的十六进制编码');
      try {
        // 尝试直接解析为JSON
        return JSON.parse(cleanEncoded);
      } catch (e) {
        return null;
      }
    }
    
    // 解密过程
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const applySaltToChar = code => textToChars(SECRET_KEY).reduce((a, b) => a ^ b, code);
    
    let decrypted;
    try {
      decrypted = cleanEncoded.match(/.{1,2}/g)
        .map(hex => parseInt(hex, 16))
        .map(applySaltToChar)
        .map(charCode => String.fromCharCode(charCode))
        .join('');
    } catch (e) {
      console.error('解密转换失败:', e);
      return null;
    }

    // 尝试解析为JSON
    try {
      return JSON.parse(decrypted);
    } catch (jsonError) {
      // 不是JSON，返回原始字符串
      return decrypted;
    }
  } catch (error) {
    console.error('解密失败:', error);
    return null;
  }
}

/**
 * 哈希密码，用于密码存储和验证
 * @param {string} password 原始密码
 * @returns {string} 哈希后的密码
 */
export const hashPassword = (password) => {
  try {
    // 使用更复杂的哈希算法
    const salt = crypto.getRandomValues(new Uint8Array(16));
    const iterations = 10000;
    const keyLength = 32;
    
    // 使用 PBKDF2 算法
    const hash = crypto.subtle.deriveBits(
      {
        name: 'PBKDF2',
        salt: salt,
        iterations: iterations,
        hash: 'SHA-256',
        length: keyLength
      },
      new TextEncoder().encode(password),
      keyLength * 8
    );
    
    // 将 salt 和 hash 组合存储
    const saltHex = Array.from(salt)
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
    const hashHex = Array.from(new Uint8Array(hash))
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
    
    return `${saltHex}:${hashHex}:${iterations}`;
  } catch (error) {
    console.error('密码哈希失败:', error);
    return null;
  }
}

/**
 * 验证密码
 * @param {string} inputPassword 用户输入的密码
 * @param {string} storedHash 存储的密码哈希
 * @returns {Promise<boolean>} 密码是否匹配
 */
export const verifyPassword = async (inputPassword, storedHash) => {
  try {
    const [saltHex, hashHex, iterations] = storedHash.split(':');
    const salt = new Uint8Array(saltHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    
    const hash = await crypto.subtle.deriveBits(
      {
        name: 'PBKDF2',
        salt: salt,
        iterations: parseInt(iterations),
        hash: 'SHA-256',
        length: 32
      },
      new TextEncoder().encode(inputPassword),
      32 * 8
    );
    
    const inputHashHex = Array.from(new Uint8Array(hash))
      .map(b => b.toString(16).padStart(2, '0'))
      .join('');
    
    return inputHashHex === hashHex;
  } catch (error) {
    console.error('密码验证失败:', error);
    return false;
  }
} 